package com.dotflat.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class Base64ToFile {
    //BASE64解码成File文件
    public static File base64ToFile(String base64, String fileName) {
        File file = null;
        //创建文件目录
        String filePath = Base64ToFile.class.getClassLoader().getResource("").getPath();
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            //截取base64头部，获取文件类型
            String fileType =".jpg";
            //去掉头部，防止转换文件后打开显示文件损坏
//            String s = base64.substring(base64.indexOf(",")+1);
//            Decoder decoder = Base64.getDecoder();
//            byte[] bytes = decoder.decode(s);

            byte[] bytes = java.util.Base64.getDecoder().decode(base64);

            file=new File(filePath+"/"+fileName+fileType);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


    public static MultipartFile base64ToMultipartFile(String base64, String fileName) {

        int index = base64.indexOf(",");

        if (index >= 0){
            //处理后缀
            String base64FileType = base64.substring(0, index);
            String ext = Base64FileTypeEnum.getFileType(base64FileType);
            if (StringUtils.isBlank(ext)){
                ext = ".jpg";
            }
            fileName = fileName + ext;

            //裁剪
            base64 = base64.substring(index + 1);
        }


        byte[] bytes = Base64.decodeBase64(base64);

        BASE64DecodedMultipartFile file = new BASE64DecodedMultipartFile(bytes, fileName);

        return file;
    }

    //File转MultipartFile
    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }


    public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            imageString = Base64.encodeBase64URLSafeString(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

    public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
//            BASE64Decoder decoder = new BASE64Decoder();
            imageString = imageString.substring(imageString.indexOf(",") + 1);
            imageByte = Base64.decodeBase64(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

}
